package com.shopping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shopping.dto.ProductCommentDTO;
import com.shopping.entity.Product;
import com.shopping.entity.ProductComment;
import com.shopping.entity.User;
import com.shopping.exception.BusinessException;
import com.shopping.mapper.ProductCommentMapper;
import com.shopping.service.ProductCommentService;
import com.shopping.service.ProductService;
import com.shopping.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductCommentServiceImpl extends ServiceImpl<ProductCommentMapper, ProductComment> implements ProductCommentService {

    @Resource
    private ProductService productService;

    @Resource
    private UserService userService;

    @Override
    public List<ProductCommentDTO> getProductComments(Long productId) {
        LambdaQueryWrapper<ProductComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductComment::getProductId, productId)
                .orderByDesc(ProductComment::getCreateTime);

        return this.list(wrapper).stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void addComment(ProductCommentDTO commentDTO) {
        // 参数校验
        if (commentDTO.getUserId() == null) {
            throw new BusinessException("用户ID不能为空");
        }
        if (commentDTO.getProductId() == null) {
            throw new BusinessException("商品ID不能为空");
        }
        if (!StringUtils.hasText(commentDTO.getContent())) {
            throw new BusinessException("评论内容不能为空");
        }
        if (commentDTO.getRating() == null || commentDTO.getRating() < 1 || commentDTO.getRating() > 5) {
            throw new BusinessException("评分必须在1-5之间");
        }

        // 检查商品是否存在
        Product product = productService.getById(commentDTO.getProductId());
        if (product == null) {
            throw new BusinessException("商品不存在");
        }

        // 检查是否已经评论过
        ProductComment existingComment = this.getOne(new LambdaQueryWrapper<ProductComment>()
                .eq(ProductComment::getUserId, commentDTO.getUserId())
                .eq(ProductComment::getProductId, commentDTO.getProductId()));
        if (existingComment != null) {
            throw new BusinessException("您已经评论过该商品");
        }

        // 获取用户信息
        User user = userService.getById(commentDTO.getUserId());
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 转换为实体并保存
        ProductComment comment = new ProductComment();
        comment.setUserId(commentDTO.getUserId());
        comment.setProductId(commentDTO.getProductId());
        comment.setUsername(user.getUsername());
        comment.setContent(commentDTO.getContent());
        comment.setRating(commentDTO.getRating());
        if (commentDTO.getImages() != null && !commentDTO.getImages().isEmpty()) {
            comment.setImages(String.join(",", commentDTO.getImages()));
        }

        this.save(comment);
    }

    @Override
    @Transactional
    public void deleteComment(Long commentId, Long userId) {
        // 检查评论是否存在且属于该用户
        ProductComment comment = this.getOne(new LambdaQueryWrapper<ProductComment>()
                .eq(ProductComment::getId, commentId)
                .eq(ProductComment::getUserId, userId));
        if (comment == null) {
            throw new BusinessException("评论不存在或无权删除");
        }

        // 删除评论
        this.removeById(commentId);
    }

    @Override
    public Double getProductRating(Long productId) {
        LambdaQueryWrapper<ProductComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductComment::getProductId, productId);

        List<ProductComment> comments = this.list(wrapper);
        if (comments.isEmpty()) {
            return 0.0;
        }

        double sum = comments.stream()
                .mapToInt(ProductComment::getRating)
                .sum();
        return sum / comments.size();
    }

    @Override
    public ProductCommentDTO getUserProductComment(Long userId, Long productId) {
        ProductComment comment = this.getOne(new LambdaQueryWrapper<ProductComment>()
                .eq(ProductComment::getUserId, userId)
                .eq(ProductComment::getProductId, productId));

        return comment != null ? convertToDTO(comment) : null;
    }

    @Override
    public List<ProductCommentDTO> getUserComments(Long userId) {
        LambdaQueryWrapper<ProductComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductComment::getUserId, userId)
                .orderByDesc(ProductComment::getCreateTime);

        return this.list(wrapper).stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void updateComment(ProductCommentDTO commentDTO) {
        // 参数校验
        if (commentDTO.getId() == null) {
            throw new BusinessException("评论ID不能为空");
        }
        if (commentDTO.getUserId() == null) {
            throw new BusinessException("用户ID不能为空");
        }
        if (commentDTO.getProductId() == null) {
            throw new BusinessException("商品ID不能为空");
        }
        if (!StringUtils.hasText(commentDTO.getContent())) {
            throw new BusinessException("评论内容不能为空");
        }
        if (commentDTO.getRating() == null || commentDTO.getRating() < 1 || commentDTO.getRating() > 5) {
            throw new BusinessException("评分必须在1-5之间");
        }

        // 检查评论是否存在且属于该用户
        ProductComment existingComment = this.getOne(new LambdaQueryWrapper<ProductComment>()
                .eq(ProductComment::getId, commentDTO.getId())
                .eq(ProductComment::getUserId, commentDTO.getUserId()));
        if (existingComment == null) {
            throw new BusinessException("评论不存在或无权修改");
        }

        // 检查商品是否存在
        Product product = productService.getById(commentDTO.getProductId());
        if (product == null) {
            throw new BusinessException("商品不存在");
        }

        // 更新评论
        existingComment.setContent(commentDTO.getContent());
        existingComment.setRating(commentDTO.getRating());
        // 处理图片列表
        if (commentDTO.getImages() != null) {
            if (commentDTO.getImages().isEmpty()) {
                existingComment.setImages(null);
            } else {
                existingComment.setImages(String.join(",", commentDTO.getImages()));
            }
        }
        existingComment.setUpdateTime(LocalDateTime.now());

        boolean success = this.updateById(existingComment);
        if (!success) {
            throw new BusinessException("更新评论失败");
        }
    }

    private ProductCommentDTO convertToDTO(ProductComment comment) {
        ProductCommentDTO dto = new ProductCommentDTO();
        dto.setId(comment.getId());
        dto.setProductId(comment.getProductId());
        dto.setUserId(comment.getUserId());
        dto.setUsername(comment.getUsername());
        dto.setContent(comment.getContent());
        dto.setRating(comment.getRating());
        dto.setCreateTime(comment.getCreateTime());
        dto.setUpdateTime(comment.getUpdateTime());

        // 处理图片列表
        if (comment.getImages() != null && !comment.getImages().isEmpty()) {
            dto.setImages(Arrays.asList(comment.getImages().split(",")));
        }

        // 获取商品信息
        Product product = productService.getById(comment.getProductId());
        if (product != null) {
            dto.setProductName(product.getName());
            dto.setProductImage(product.getImageUrl());
        }

        return dto;
    }
}